package com.example.springboot.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.example.springboot.pojo.Result;
import com.example.springboot.pojo.Validation;
import com.example.springboot.service.ValidationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.example.springboot.util.SendMail;

import java.util.Date;

@RestController
@RequestMapping("/validation")
public class ValidationController {

    @Autowired
    private ValidationService validationService;

    private Validation[] findValidation(String email) {
//        System.out.println("00000");
        Validation[] v = validationService.findValidation(email);
//        System.out.println("--------------");
        return v;
    }

    private void deleteValidation(String email) {
        validationService.deleteValidation(email);
    }

//    public boolean checkValidation(String email, String code) {
//        System.out.println(email);
//        System.out.println(code);
//        Validation v = findValidation(email);
//        System.out.println(v.getCode()); //``````````````````````````````````````````````
//        return code.equals(v.getCode());
//    }

    private void sendEmail(String email) {
        String code = RandomUtil.randomNumbers(4);
        String msg = "尊敬的客户，您的验证码是：" + code + "，可用于验证您的邮箱。请妥善保管，打死都不要告诉别人。";
        SendMail.Mail_Code(email, "【邮箱验证】", msg);
        //将验证码存入数据库中
        validationService.saveCode(email, code, DateUtil.offsetMinute(new Date(), 5));
    }

    @PutMapping("/")
    public Result<?> sendValidation(String email) {
        Validation[] v = findValidation(email);
        if (v.length == 0) {
            sendEmail(email);
            return Result.success();
        } else {
            deleteValidation(email);
            sendEmail(email);
            return Result.success();
        }
    }
}
